package com.csyf.manager.controller;

import com.csyf.manager.entity.CardInfoVo;
import com.csyf.manager.exception.ApiValidateException;
import com.csyf.manager.utils.FileUtil;
import com.csyf.manager.utils.ReturnData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: casper
 * @Description: Excel模板下载
 * @Date: Created in 2018/9/19 14:50
 */
@Slf4j
@Controller
@RequestMapping(value = "/boss/batch")
public class BatchPaymentController {

    /**
     * 下载excel模板
     *
     * @param response
     */
    @ResponseBody
    @RequestMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "base.xlsx";
        try {
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(new File("/home/csyf/excel/template/" + fileName)));
            response.setContentType("application/zip");
            OutputStream out = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment; filename="+"base"+".xlsx");
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if(b!=-1) out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("模板下载失败");
        }
    }

    /**
     * 上传Excel文件
     */
    public String uploadAccessory(MultipartFile file) throws Exception {
        String contentType = file.getContentType();   //文件类型
        String fileName = "";
        String filePath = "/home/csyf/excel/";

        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

        if ("xlsx".equals(suffix) || "xls".equals(suffix)) {

            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            fileName = df.format(calendar.getTime()) + "." + suffix;

            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
        } else {
            throw new ApiValidateException("文件类型不支持，请重新上传");
        }


        return filePath + fileName;
    }

    /**
     * 读取excel内容
     */
    @ExceptionHandler
    @ResponseBody
    @RequestMapping(value = "readExcel", method = RequestMethod.POST)
    public ReturnData readxls(@RequestParam("file") MultipartFile file) {
        Map<String,Object> resultMap = new HashMap<>();
        ReturnData returnData = new ReturnData();
        List<CardInfoVo> list = null;

        if (file.isEmpty()) {
            returnData.setCode(99);
            returnData.setMsg("文件不存在");
            return returnData;
        }

        try {
            //上传文件至服务器
            String filePath = uploadAccessory(file);

            //读取文件内容以及校验
            list = FileUtil.readxls(filePath);

            resultMap.put("list", list);
            resultMap.put("filePath", filePath);

            returnData.setCode(0);
            returnData.setMsg("读取成功");
            returnData.setData(resultMap);
            returnData.setCount(list.size());
            return returnData;

        } catch (ApiValidateException e) {
            returnData.setCode(99);
            returnData.setMsg(e.getMessage());
            return returnData;
        } catch (Exception e) {
            returnData.setCode(99);
            returnData.setMsg("网络错误，请联系技术人员");
            return returnData;
        }
    }



}
